/**
 * Created by LiuDan on 2017/07/01.
 * 注册.js
 */
;(function($){
    //公共方法
    $.commonJs={
        //取url里面参数
        getString:function(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return decodeURIComponent(r[2]);
            return null;
        },
        //弱提示
        comPop: function (text,callback) {
            var str = '<div class="layer layerOut"><p></p></div>'
            if ($('body').find('.layer').length<= 0) {
                $('body').append(str);
            }
            $('.layer').show();
            $('.layer p').html(text)
            setTimeout(function() {
                $('.layer').remove();
                callback;
            },2000)
        },
        ajaxLoading:function(obj,text,bool){
            obj.html(text)
            if(bool){
                obj.addClass('loginenable')
            }else{
                obj.removeClass('loginenable')
            }
        },
        //loading...
        setPageLoading:function (boolShowing) {
            var loading='<div class="loadImg dn" id="loadPage"><img src="/web/images/login/loading.svg"/></div>'
            if( $('body').find('.loadImg').length==0){
                $('body').append(loading);
            }
            $('#loadPage')[boolShowing ? 'show' : 'hide']();
            return  this;
        },
        //错误提示
        errorStyle:function(){
            return {"border":"1px solid #ff4012"}
        },
        //输入框清空与显示
        clearInp:function(inp,errorTip,success){
            var inptext =inp.val();
            if (inptext == "") {
                errorTip.hide();
                success.hide()
            } else {
                errorTip.show();
            }
            return false;
        },
        //清空按钮
        closeBtn:function(){
            $(".close").click(function () {
                $(this).parent().find('input').val("");
                $(this).parent().find('input').css({"border": "1px solid #3492fd"});
                $(this).hide()
            });
        },
        //输入框获取焦点
        Inpfocus:function(inp,tips){
            tips.css("display", "none");
            inp.css("border", "1px solid #3492fd");
        }
    };
    //DOM 获取
    $.domEvt={
        /*----------------------------注册DOM获取-----------------------------------*/
        phoneInput:$('.registerUsernameBox .Rusername'), //手机号input
        phoneLogin:$('.registerUsernameBox .RuserNameHit'),//手机号提示
        phoneLoginInfo:$(".registerUsernameBox .HitWord"), //手机号 提示文字

        imgCodeInp:$('.imgVertifyCode .imgVertify'), //图形码 input
        imgLogin:  $('.imgVertifyCode .RverificationCodeHit'), //图形码 提示
        imgLoginInfo:  $('.imgVertifyCode .HitWord'),//图形码 提示文字

        verCodeInput:$('.verification-code .verifCode'),//验证码 input
        verLogin:$('.verification-code .RverificationCodeHit'),//验证码 提示
        verLoginInfo:$('.verification-code .HitWord'),//验证码 提示文字
        verLoginBtn: $('.verification-code .btn-getcode'),//获取验证码btn

        passwordInp:$('.registerPassword .Rpassword'),
        passWordInfo:$('.registerPassword .HitWord'),//密码 提示文字
        passWord:$('.registerPassword .RpassowrdHit')//验证码 提示

    }
    //表单验证
    $.registerEvt={
        checkTell:false,
        //手机号 正则
        regPhone:function(tel){
            var regPhone=/^1\d{10}$/;
            if(regPhone.test(tel)){
                return true;
            }else{
                return false;
            }
        },
        //邮箱正则
        regEmail:function(eml){
            var regEmail=/^\w+([-+.]\w+)*@\w+([-.]\w{2,})*\.\w{2,}([-.]\w{2,})*$/;
            if(regEmail.test(eml)){
                return true;
            }else{
                return false;
            }
        },
        //密码正则
        passwordReg:function(pw){
            var reg=/^(?!\s+)[\w\W]{6,18}$/;
            if(reg.test(pw)){
                return true;
            }else{
                return false;
            }
        },
        //登陆密码验证
        passWordReg:function(){
            var cyinput2Length=$.domEvt.logPassInput.val().trim().length;
            if (cyinput2Length== 0) {
                $.domEvt.logPassInput.css($.commonJs.errorStyle());
                $.domEvt.cymyPassInfo.text("请输入6-18位密码!");
                $.domEvt.cymyPass.css("display", "block");
                return false
            } else if (cyinput2Length < 6 || cyinput2Length > 18) {
                $.domEvt.logPassInput.css("border", "2px solid #ff4012").val("");
                $.domEvt.cymyPassInfo.text("请输入6-18位密码!");
                $.domEvt.cymyPass.css("display", "block");
                return false
            } else {
                $.domEvt.logPassInput.css("border", "");
                return true
            }
        },
        //注册密码验证
        regPassword:function(){
            var passwVal=$.domEvt.passwordInp.val().trim();
            if(passwVal.length==0){
                $.domEvt.passwordInp.css($.commonJs.errorStyle());
                $.domEvt.passWordInfo.text("请输入6-18位密码!");
                $.domEvt.passWord.show();
                return false
            }else if($.registerEvt.passwordReg(passwVal)==false){
                $.domEvt.passwordInp.css($.commonJs.errorStyle());
                $.domEvt.passWordInfo.text("密码格式不正确,请输入6-18位密码!");
                $.domEvt.passWord.show();
                $('.passloginsuccess').hide();
                return false
            }else{
                $.domEvt.passwordInp.css("border", "");
                $('.passloginsuccess').show();
                $('.RpasswordClose').hide()
                return true
            }

        },
        //手机号验证
        phoneReg:function(){
            var phoneTxt=$.domEvt.phoneInput.val().trim();
            if(phoneTxt.length==0){
                $.domEvt.phoneInput.css($.commonJs.errorStyle());
                $.domEvt.phoneLoginInfo.text("请输入手机号!");
                $.domEvt.phoneLogin.show();
                return false
            }else if($.registerEvt.regPhone(phoneTxt)==false){
                $.domEvt.phoneInput.css($.commonJs.errorStyle());
                $.domEvt.phoneLoginInfo.text("手机格式不正确!");
                $('.cymyloginsuccess').hide();
                $.domEvt.phoneLogin.show();
                return false
            }else{
                return true
            }
        },
        //图形验证码
        imgCodeReg:function(){
            var codeLen=$.domEvt.imgCodeInp.val().trim().length;
            if(codeLen==0){
                $.domEvt.imgCodeInp.css($.commonJs.errorStyle());
                $.domEvt.imgLoginInfo.text("请输入图形验证码!");
                $.domEvt.imgLogin.show();
                return false;
            }else{
                $.domEvt.imgCodeInp.css("border", "");
                return true
            }
        },
        //动态验证码验证
        cymCodeInfo:function(){
            var cymCodeLen=$.domEvt.verCodeInput.val().trim().length;
            if(cymCodeLen==0){
                $.domEvt.verCodeInput.css($.commonJs.errorStyle());
                $.domEvt.verLoginInfo.text("请输入动态验证码!");
                $.domEvt.verLogin.show();
                return false;
            }else if(cymCodeLen < 4){
                $.domEvt.verCodeInput.css($.commonJs.errorStyle());
                $.domEvt.verLoginInfo.text("请输入4位动态验证码!");
                $.domEvt.verLogin.show();
                return false;
            }else{
                $.domEvt.verCodeInput.css("border", "");
                return true
            }
        }
    }
    //手机号注册逻辑
    $.validate={
        bindevent:function(){
            //同意
            $(".allowProtocal,.allow").click(function () {
                $('.allowProtocal').toggleClass("select").siblings().removeClass("select");
                if($('.allowProtocal').hasClass('select')){
                    $('.goRegister').removeClass('registerProtocal')
                }else{
                    $('.goRegister').addClass('registerProtocal')
                }
            });
            //点击切换图形验证码
            $(".imgVertifyCode .imgCode").on("click",function(){
                var a=Math.random();
                $(this).attr("src","/captcha/default?t="+a+"");
            });
            //用户协议
            $('.allowProtocalUnderline').click(function(){
                $('.protocol-shadow').show();
            })
            $('.pay-protocol-close').click(function(){
                $('.protocol-shadow').hide();
            })
            //输入框 获取焦点
            $.domEvt.phoneInput.focus(function () {
                $.commonJs.Inpfocus($(this),$.domEvt.phoneLogin)
            });
            $.domEvt.imgCodeInp.focus(function () {
                $.commonJs.Inpfocus($(this),$.domEvt.imgLogin)
            });
            $.domEvt.verCodeInput.focus(function () {
                $.commonJs.Inpfocus($(this),$.domEvt.verLogin)
            });
            $.domEvt.passwordInp.focus(function () {
                $.commonJs.Inpfocus($(this),$.domEvt.passWord);

            });
            //输入框 清空事件 --手机号输入框
            $.domEvt.phoneInput.on("input", function () {
                $('.cymyloginsuccess').hide();
                var close=$(this).parent().find('.close')
                $.commonJs.clearInp($.domEvt.phoneInput,close,$('.cymyloginsuccess'))
            });
            //输入框 清空事件 --密码
            $.domEvt.passwordInp.on("input", function () {
                if($.domEvt.passwordInp.val().length<6||$.domEvt.passwordInp.val().length>18){
                    $('.passloginsuccess').hide()
                }
                var close=$(this).parent().find('.close')
                $.commonJs.clearInp($.domEvt.passwordInp,close,$('.passloginsuccess'))
            });
            $.commonJs.closeBtn();//清空按钮点击事件
            //手机号 失去焦点
            $.domEvt.phoneInput.blur(function(){
                $.registerEvt.phoneReg()
                if($.registerEvt.phoneReg()){
                    RequestService("/online/user/valiAccount", "POST", {username:$.domEvt.phoneInput.val().trim(), '_token': $("input[name='_token']").val(),}, function (result) {
                        if(result.resultObject == 400){
                            $.domEvt.phoneInput.css($.commonJs.errorStyle());
                            $.domEvt.phoneLoginInfo.text("手机号已注册!");
                            $('.cymyloginsuccess').hide();
                            $.domEvt.phoneLogin.show();
                        }else{
                            $.domEvt.phoneInput.css("border", "");
                            $('.cymyloginsuccess').show();
                            $('.RusernameClose').hide();
                            $.registerEvt.checkTell=true;
                        }
                    });
                }
            });
            //图形验证码
            $.domEvt.imgCodeInp.blur(function () {
                $.registerEvt.imgCodeReg()
            });
            //手机验证码
            $.domEvt.verCodeInput.blur(function () {
                $.registerEvt.cymCodeInfo()
            });
            //密码
            $.domEvt.passwordInp.blur(function(){
                $.registerEvt.regPassword()
            });
            //获取动态验证码
            $(".btn-getcode").click(function(){
                var _this=$(this)
                var tel = $.domEvt.phoneInput.val().trim();
                var imgcode=$.domEvt.imgCodeInp.val().trim();
                var _token = $("input[name='_token']").val();
                var data = {phone: tel, vtype:1,captcha:imgcode,_token:_token};
                if(!$.registerEvt.phoneReg()&&!$.registerEvt.checkTell){
                    return;
                }else if(!$.registerEvt.imgCodeReg()){
                    return;
                }else{
                    _this.addClass('enable')
                    //ajax
                    RequestService("/online/verificationCode/sendmessage", "POST", data, function (result) {
                        if(result.success){
                            $.commonJs.comPop(result.message);
                            var second = 90;
                            var oldval = _this.val();
                            var timer = setInterval(function () {
                                _this.text(second-- + "s");
                                _this.addClass("enable");
                                if (second === 0 || _this.val() != oldval) {
                                    second = 0;
                                    _this.removeClass("enable");
                                    _this.css('cursor','pointer');
                                    _this.text("获取动态码");
                                    clearInterval(timer);
                                }
                            }, 1000)
                        }else{
                            var errorTxt=result.errorMessage;
                            _this.removeClass('enable')
                            if(errorTxt=="同一手机号两次发送间隔至少90秒！"){
                                $.domEvt.phoneInput.css($.commonJs.errorStyle());
                                $.domEvt.phoneLoginInfo.text(result.errorMessage);
                                $.domEvt.phoneLogin.show();
                            }else if(errorTxt.indexOf('手机号')!=-1&&errorTxt!='同一手机号两次发送间隔至少90秒！'){
                                $.domEvt.phoneInput.css($.commonJs.errorStyle());
                                $.domEvt.phoneLoginInfo.text(result.errorMessage);
                                $.domEvt.phoneLogin.show();
                            }else if(errorTxt.indexOf('验证码')!=-1){
                                $.domEvt.imgCodeInp.css($.commonJs.errorStyle());
                                $.domEvt.imgLoginInfo.text(result.errorMessage);
                                $.domEvt.imgLogin.show();
                            }else{
                                $.commonJs.comPop('动态验证码发送次数超限~')
                            }
                        }

                    })
                }
            })
            var referUrl=$.commonJs.getString('refer')?$.commonJs.getString('refer'):'';
            //注册 ajax
            $('.goRegister').click(function(){
                var _this=$(this)
                if(!$.registerEvt.phoneReg()){
                    return;
                }else if(!$.registerEvt.imgCodeReg()){
                    return;
                }else if(!$.registerEvt.cymCodeInfo()){
                    return;
                }else if(!$.registerEvt.regPassword()){
                    return;
                }else if(!$('.allowProtocal').hasClass('select')){
                    return;
                }else{
                    $.commonJs.ajaxLoading(_this,'注册中...',true);
                    var did = zhuge.getDid();
                    var data={
                        username:$.domEvt.phoneInput.val().trim(),
                        password:$.domEvt.passwordInp.val().trim(),
                        code:$.domEvt.verCodeInput.val().trim(),
                        vcode:$.domEvt.imgCodeInp.val().trim(),
                        registType:2,
                        _token:$('input[name=_token]').val(),
                    }
                    var loginData={
                        username: $.domEvt.phoneInput.val().trim(),
                        password: $.domEvt.passwordInp.val().trim(),
                        additional:did
                    }
                    $.ajax({
                        type:"POST",
                        url:"/online/user/phoneRegist",
                        async:true,
                        data:data,
                        xhrFields: {
                            withCredentials: true
                        },
                        crossDomain: true,
                        beforeSend: function(request) {
                            request.setRequestHeader("bxg-platform", "pc");
                        },
                        success:function(result){
                            if (result.success) {
                                $.commonJs.comPop('注册成功,立即登录~',function(){
                                    sessionStorage.setItem('phoneNumber',$.domEvt.phoneInput.val());
                                    window.localStorage.userName=loginData.username;
                                    setTimeout(function(){
                                        if(referUrl!=''){
                                            location.href = referUrl;
                                        }else{
                                            location.href = "/";
                                        }
                                        var myStudent=window.localStorage.myStudyCenter;
                                        var myFeedback=window.localStorage.myFeedback;
                                        if(myStudent==1){
                                            window.location.href="/web/html/myStudyCenter.html";
                                            window.localStorage.myStudyCenter=null;
                                        }
                                        if(myFeedback==1){
                                            window.location.href="/web/html/personcenter.html";
                                            window.localStorage.myFeedback=null;
                                        }
                                        if(getQueryString('src')==='bbs'){
                                            $("#hidden_frame").attr("src","../../bbsLogin.jsp");
                                            //延迟执行一下以保证iframe执行了
                                            setTimeout(function () {
                                                location.href = basePathBBS;//跳转到bbs首页
                                            }, 1000);
                                        }
                                    },1000)

                                }())
                            } else {
                                $.commonJs.ajaxLoading(_this,'注册登录',false)
                                if (result.errorMessage == "动态验证码错误1" || result.errorMessage == "动态验证码错误2") {
                                    $.domEvt.verCodeInput.css($.commonJs.errorStyle());
                                    $.domEvt.verLoginInfo.text("动态码错误!");
                                    $.domEvt.verLogin.show();
                                } else if(result.errorMessage=="此手机号已被注册"){
                                    $.domEvt.phoneInput.css($.commonJs.errorStyle());
                                    $.domEvt.phoneLoginInfo.text("此手机号已被注册!");
                                    $.domEvt.phoneLogin.show();

                                }else if(result.errorMessage=="图形验证码不合法或无效"){
                                    $.domEvt.imgCodeInp.css($.commonJs.errorStyle());
                                    $.domEvt.imgLoginInfo.text('验证码错误!');
                                    $.domEvt.imgLogin.show();
                                }else if(result.errorMessage=="动态码超时，请重新发送！"){
                                    $.domEvt.verCodeInput.css($.commonJs.errorStyle());
                                    $.domEvt.verLoginInfo.text(result.errorMessage);
                                    $.domEvt.verLogin.show();
                                }else if(result.errorMessage=="此用户已注册"){
                                    $.domEvt.phoneInput.css($.commonJs.errorStyle());
                                    $.domEvt.phoneLoginInfo.text("此用户已注册!");
                                    $.domEvt.phoneLogin.show();

                                }else{
                                    $.commonJs.comPop(result.errorMessage)
                                }
                            }
                        },
                        error:function(result){
                            $.commonJs.comPop('系统繁忙,请稍后再试~')
                        }
                    });
                }
            })
        },
        //触发事件
        init:function(){
            $.validate.bindevent();
        }
    }
    zhuge.track('Web_进入注册页');
    //注册入口
    $.validate.init();
})(jQuery)